package com.examination.system.administrator.service.impl;

import com.alibaba.fastjson.JSON;
import com.examination.framework.exception.ExceptionCast;
import com.examination.framework.model.response.CommonCode;
import com.examination.framework.model.response.QueryResponseResult;
import com.examination.framework.model.response.QueryResult;
import com.examination.framework.model.response.ResponseResult;
import com.examination.framework.utils.VisitURLUtil;
import com.examination.system.administration.Department;
import com.examination.system.administration.Employee;
import com.examination.system.administration.response.*;
import com.examination.system.administrator.dao.DepartmentMapper;
import com.examination.system.administrator.dao.DepartmentRepository;
import com.examination.system.administrator.dao.EmployeeMapper;
import com.examination.system.administrator.dao.EmployeeRepository;
import com.examination.system.administrator.service.DepartmentService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.persistence.Transient;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

/**
 * @author 寇淇芮
 * @Date 2019/9/14 9:50
 */
@Service
public class DepartmentServiceImpl implements DepartmentService {


    @Value("${administrator.mobilePhone.url}")
    private String mobilePhoneUrl;

    @Autowired
    private DepartmentRepository departmentRepository;

    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private EmployeeRepository employeeRepository;


    @Override
    @Transient
    @Transactional
    public AddAdministrationResult addDepartment(Department department) {
        Assert.notNull(department,"数据为空");

        if(StringUtils.isEmpty(department.getDepartmentName().trim())){
            ExceptionCast.cast(DepartmentCode.invalidBlendingNumber);
        }
        //判断人事部里面是否存在这个人
      if(StringUtil.isNotEmpty(department.getDepartmentName())&&StringUtils.isNotEmpty(department.getDepartmentLeader())){
                if(this.employeeByName(department.getDepartmentLeader().trim())== null){
                    ExceptionCast.cast(DepartmentCode.noEmployee);
                }
          //判断手机号是否正确
          //1.1验证手机号
          try {
              if(this.verificationPhone(department.getTelePhone())){
                  ExceptionCast.cast(DepartmentCode.invalidMobilePhoneNumber);
              }
          }catch (Exception e){
              ExceptionCast.cast(CommonCode.FAIL);
          }
          //判断数据是否重复
          //判断员工同时管多个部门  不允许
          if((this.departmentByName(department.getDepartmentName().trim())!=null)||(this.departmentByLeader(department.getDepartmentLeader().trim())!=null)){
              ExceptionCast.cast(DepartmentCode.dataDuplication);
          }
         }



        //id
        department.setDepartmentId(UUID.randomUUID().toString().replace("-","").toUpperCase());
        department.setDepartmentNumber(0);
        /*if(StringUtils.isNotEmpty(department.getDepartmentName())){
            if(StringUtils.isEmpty(department.getTelePhone())){
                ExceptionCast.cast(DepartmentCode.invalidBlendingNumber);
            }
        }*/
        return departmentRepository.save(department) !=null ? new AddAdministrationResult(CommonCode.SUCCESS,department.getDepartmentId()): new AddAdministrationResult(CommonCode.FAIL, department.getDepartmentId());
    }

    @Override
    @Transient
    @Transactional
    public DeleteAdministrationResult deleteDepartmentById(String departmentId, String newDepartmentName, Department department) {

        newDepartmentName = newDepartmentName.trim();
        Department newDepartment = this.departmentByName(newDepartmentName);
        //先查询新的部门名称是否存在
        //1.1判断是否有值
        if(StringUtils.isEmpty(newDepartmentName.trim())||StringUtils.isEmpty(departmentId.trim())||newDepartment==null){
            ExceptionCast.cast(DepartmentCode.invalidBlendingNumber);
        }

        //查询当前的部门是否存在
        if( this.departmentById(departmentId)==null ){
            ExceptionCast.cast(DepartmentCode.invalidBlendingNumber);
        }
        //删除该部门信息
       if(departmentMapper.deleteByDepartmentId(departmentId.trim()) == 0){
           ExceptionCast.cast(DepartmentCode.failedToDeleteData);
       }
        //修改员工信息
        Integer quantity = employeeMapper.upateEmployeeByDepartmentName(departmentId, newDepartment.getDepartmentId());
        //修改部门信息
        if(quantity >0){
            departmentMapper.upateDepartmentByDepartmentName(newDepartmentName,quantity);
        }
        return new DeleteAdministrationResult(CommonCode.SUCCESS,departmentId);
    }



    @Override
    @Transient
    @Transactional
    public ResponseResult editDepartmentById(String departmentId, Department department) {
        departmentId = departmentId.trim();

        if(StringUtils.isEmpty(departmentId)||StringUtils.isEmpty(department.getDepartmentName())){
            ExceptionCast.cast(DepartmentCode.invalidBlendingNumber);
        }
        //判断修改数据与id是否一致
        if(!departmentId.equals(department.getDepartmentId().trim())){
            ExceptionCast.cast(DepartmentCode.inconsistentAmendments);
        }
        //判断数据库是否存在
        Department one = this.departmentById(departmentId);
        String phone = department.getTelePhone().trim();
        if( one == null){
            ExceptionCast.cast(DepartmentCode.dataDoesNotExist);
        }
        //判断修改员工名是否一致
        if(one.getDepartmentName().trim().equals(department.getDepartmentName().trim())){

            if(StringUtils.isEmpty(phone)){
                ExceptionCast.cast(DepartmentCode.invalidBlendingNumber);
            }

            //如果一致判断员工手机号是否一样
            if(StringUtils.isEmpty(one.getTelePhone())||!one.getTelePhone().trim().equals(department.getTelePhone().trim())){
                //如果不一样就判断手机号是否正确{
                try{
                    if(this.verificationPhone(phone)){
                        ExceptionCast.cast(DepartmentCode.invalidMobilePhoneNumber);
                    }
                }catch (Exception e){
                    ExceptionCast.cast(CommonCode.FAIL);
                }
            }
        }else{
            //判断员工是否存在
            Employee employee = this.employeeByName(department.getDepartmentLeader());
            if(employee == null){
                ExceptionCast.cast(DepartmentCode.noEmployee);
            }
            if(!employee.getThePhone().equals(department.getTelePhone())){
                //如果不一样就判断手机号是否正确{
                try{
                    if(this.verificationPhone(phone)){
                        ExceptionCast.cast(DepartmentCode.invalidMobilePhoneNumber);
                    }
                }catch (Exception e){
                    ExceptionCast.cast(CommonCode.FAIL);
                }
            }

        }
        return departmentRepository.save(department) == null ? new ResponseResult(CommonCode.FAIL):new ResponseResult(CommonCode.SUCCESS);
    }

    @Override
    public QueryResponseResult findDepartmentList(Integer pages, Integer size, Department department) {
        int minSize = 10;
        int maxSize = 25;
        int minPage = 1;
        if (pages<minPage){
            pages = 1;
        }
        if(size<minSize || size > maxSize){
            size = 10;
        }

        PageHelper.startPage(pages,size);
        Page<Department> areaTypList = departmentMapper.findDepartment();
        //回写
        QueryResult queryResult = new QueryResult();
        //显示的记录
        queryResult.setList(areaTypList.getResult());
        //一共的条数
        queryResult.setTotal(areaTypList.getTotal());
        //返回数据
        return new QueryResponseResult(AreaTypeCode.SUCCESS,queryResult);
    }

    @Override
    public QueryResponseResult findDepartmentList() {
        List<Department> departmentList = departmentRepository.findAll();
        QueryResult queryResult = new QueryResult();
        //显示的记录
        queryResult.setList(departmentList);
        //一共的条数
        queryResult.setTotal(Long.valueOf(departmentList.size()));
        //返回数据
        return new QueryResponseResult(AreaTypeCode.SUCCESS,queryResult);
    }

    private Employee employeeByName(String employeeName) {
        List<Employee> employeeList = employeeRepository.findByName(employeeName);
        return employeeList.size() == 0 ? null : employeeList.get(0);
    }


    /**
     * 判断是否存在数据
     * @param departmentName
     * @return
     */
    private Department departmentByName(String departmentName) {
        List<Department> departmentList = departmentRepository.findByDepartmentName(departmentName);
        return  departmentList.size() > 0 ? departmentList.get(0) : null;
    }

    /**
     *
     * @param leader
     * @return
     */
    private Department departmentByLeader(String leader){
        List<Department> departmentList = departmentRepository.findByDepartmentLeader(leader);
        return departmentList.size() > 0 ? departmentList.get(0) : null;
    }
    /**
     * 判断是否是有效手机号
     * @param phone  手机号
     * @return 是否存在
     */
    private boolean verificationPhone(String phone) throws Exception {
        String msg = VisitURLUtil.getData(mobilePhoneUrl + phone, "GBK");
        ZoneResult zoneResult = JSON.parseObject(msg.substring(msg.indexOf("=")+1), ZoneResult.class);
        return StringUtil.isNotEmpty(zoneResult.getMts())? false :true;
    }

    /**
     *
     * @param departmentId
     * @return
     */
    private Department departmentById(String departmentId) {
        Optional<Department> optional = departmentRepository.findById(departmentId);
        if(optional.isPresent()){
            return optional.get();
        }
        return null;
    }
}
